#!/usr/bin/python
from SimpleXMLRPCServer import SimpleXMLRPCServer
import subprocess as subp
import lpantilt
import time
import socket
import thread
import os

from ctypes import cdll

class Dir :
	UP = "UP>"
	DOWN = "DOWN>"
	LEFT = "LEFT>"
	RIGHT = "RIGHT>"
	RESET = "RESET>"


class KeySimulator :
	PRESS_UP = 0
	PRESS_DOWN = 1
	PRESS_LEFT = 2
	PRESS_RIGHT = 3
	PRESS_ENTER = 4
	PRESS_ESC = 5
	PRESS_HOME = 6

	def __init__(self):
		self.lib = cdll.LoadLibrary("./lib/Util_KeyPressSimulator.so")
		self.lib.init_sim()

	def simPress(self, key):
		if key == "UP" :
			self.lib.press(self.PRESS_UP)
		elif key == "DOWN" :
			self.lib.press(self.PRESS_DOWN)
		elif key == "LEFT" :
			self.lib.press(self.PRESS_LEFT)
		elif key == "RIGHT" :
			self.lib.press(self.PRESS_RIGHT)
		elif key == "HOME" :
			self.lib.press(self.PRESS_HOME)

			# close firefox
			os.system("kill -9 $(pidof firefox)")
			os.system("wmctrl -s 0")
			os.system("rm ~/.qlive/conference/Tmp_ProgramIsRunning.qlive")

		elif key == "B" :
			self.lib.press(self.PRESS_ESC)
		elif key == "A" :
			self.lib.press(self.PRESS_ENTER)

		print "simulating " + key

class CameraControl :
	def __init__(self):	
		self.lpt = lpantilt.Lpantilt("/dev/video0")
		self.stop = False
		self.key_simulator = KeySimulator()

	def move(self, drt):
		self.stop = False
		if drt == Dir.UP :
			thread.start_new_thread(self.startTilt,(0,-2))
		elif drt == Dir.DOWN:
			thread.start_new_thread(self.startTilt,(0,2))
		elif drt == Dir.LEFT :
			thread.start_new_thread(self.startTilt,(-2,0))
		elif drt == Dir.RIGHT :
			thread.start_new_thread(self.startTilt ,(2,0))
		elif drt == Dir.RESET :
			self.lpt.reset()
		else :
			self.stopMove()


	def startTilt(self, pan, tilt):
		while not self.stop :
			self.lpt.pantilt(pan, tilt)
			print "tilt ..."
	
	def startPan(self, pan):
		while not self.stop :
			self.lpt.pan(pan)	
			print "panning ..."

	def stopMove(self):
		self.stop = True
		print "stop..."


	def updateState(self, state):
		print "new state = ", state

		if state == "B-UP" :
			self.move(Dir.UP)
		elif state == "B-DOWN" :
			self.move(Dir.DOWN)
		elif state == "B-LEFT" :
			self.move(Dir.LEFT)
		elif state == "B-RIGHT" :
			self.move(Dir.RIGHT)
		elif state == "B-A" :
			self.move(Dir.RESET)
		else :
			print "else state " + state
			self.key_simulator.simPress(state)
			self.move(state)

if __name__ == "__main__" :
	c = CameraControl()
	server = SimpleXMLRPCServer( ("localhost", 19191) )
	server.register_function(c.updateState)
	
	print "service start @localhost 19191 forever"
	server.serve_forever()


